﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;

namespace ZBJF.Warranty.BLL
{
    public partial class InsuranceProductOrderService
    {
        public InsuranceProductOrder LoadById(long id)
        {
            return LoadEntities(o => o.ID == id).FirstOrDefault();
        }
        public InsuranceProductOrder LoadByOrderNo(string orderNo)
        {
            return LoadEntities(o => o.OrderNo.Equals(orderNo)).FirstOrDefault();
        }
        public int GetSellerEmloyeeSaleQty(long sellerEmpployeeId)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrder>();
            expressionWhere = expressionWhere.And(o => o.SellerEmployeeID == sellerEmpployeeId);
            expressionWhere = expressionWhere.And(o => o.Status == (byte)InsuranceProductOrderStatus.Paid);
            var list = LoadEntities(expressionWhere);
            return list.Any() ? list.Sum(o => o.BuyCount) : 0;
        }

        public bool PayOrderAndCreateCard(string orderNo)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    var insuranceProductOrder = ServiceFactory.InsuranceProductOrderServiceInstance.LoadByOrderNo(orderNo);
                    insuranceProductOrder.PayTime = DateTime.Now;
                    insuranceProductOrder.Status = (byte)InsuranceProductOrderStatus.Paid;
                    var result = ServiceFactory.InsuranceProductOrderServiceInstance.UpdateEntities(insuranceProductOrder);
                    if (result)
                    {
                        if (insuranceProductOrder.BuyCount > 0)
                        {
                            var insuranceCard = new InsuranceProductOrderCard()
                            {
                                InsuranceProductOrderId = insuranceProductOrder.ID,
                                SellerInsuranceProductId = insuranceProductOrder.SellerInsuranceProductID,
                                SellerEmployeeID = insuranceProductOrder.SellerEmployeeID,
                                SellerEmployeeName = insuranceProductOrder.SellerEmployeeName,
                                BuyUserName = insuranceProductOrder.BuyUserName,
                                BuyUserIDNo = insuranceProductOrder.BuyUserIDNo,
                            };
                            result = ServiceFactory.InsuranceProductOrderCardServiceInstance.CreateCard(insuranceProductOrder.BuyCount,
                                  insuranceCard);
                        }
                    }
                    ts.Complete();
                    return result;
                }
                catch (Exception)
                {
                    ts.Dispose();
                    return false;
                }
            }
        }

        public IQueryable<InsuranceProductOrder> GetPagingList(InsuranceProductOrderModel model, out int total)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrder>();
            if (model.SellerEmployeeID.HasValue)
            {
                expressionWhere = expressionWhere.And(o => o.SellerEmployeeID == model.SellerEmployeeID.Value);
            }
            if (model.Status.HasValue)
            {
                if (model.Status.Value == (byte)InsuranceProductOrderStatus.TimeOutCancel ||
                    model.Status.Value == (byte)InsuranceProductOrderStatus.UserCancel) //取消
                {
                    expressionWhere = expressionWhere.And(o => o.Status == (byte)InsuranceProductOrderStatus.TimeOutCancel ||
                    o.Status == (byte)InsuranceProductOrderStatus.UserCancel);
                }
                else
                {
                    expressionWhere = expressionWhere.And(o => o.Status == model.Status.Value);
                }
            }
            if (model.MonthDateTime.HasValue) //获取某一个月的订单
            {
                var dtMonth = model.MonthDateTime.Value.ToString("yyyyMM");
                expressionWhere = expressionWhere.And(o => SqlFunctions.DateName("yyyy", o.CreateOrderTime) + SqlFunctions.DateName("MM", o.CreateOrderTime) == dtMonth);
            }
            return LoadPagerEntities<InsuranceProductOrder>(model.PageIndex, model.iDisplayLength, out total, expressionWhere, model.iSorts);
        }

        public decimal GetSellerInsuranceProductSaleIncome(string dtMonth, long employeeId, long sellerInsuranceProductId = 0, InsuranceProductOrderStatus status = 0)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrder>();
            if (!string.IsNullOrEmpty(dtMonth))
            {
                expressionWhere = expressionWhere.And(o => SqlFunctions.DateName("yyyy", o.CreateOrderTime) + SqlFunctions.DateName("MM", o.CreateOrderTime) == dtMonth);
            }
            if (employeeId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerEmployeeID == employeeId);
            }
            if (sellerInsuranceProductId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerInsuranceProductID == sellerInsuranceProductId);
            }
            if ((byte)status > 0)
            {
                expressionWhere = expressionWhere.And(o => o.Status == (byte)status);
            }
            var list = LoadEntities(expressionWhere);
            return list.Any() ? list.Sum(o => o.SaleRetailPrice) : 0;
        }

        public long GetSellerInsuranceProductSaleCount(string dtMonth, long employeeId, long sellerInsuranceProductId,
            InsuranceProductOrderStatus status = 0)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrder>();
            if (!string.IsNullOrEmpty(dtMonth))
            {
                expressionWhere = expressionWhere.And(o => SqlFunctions.DateName("yyyy", o.CreateOrderTime) + SqlFunctions.DateName("MM", o.CreateOrderTime) == dtMonth);
            }
            if (employeeId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerEmployeeID == employeeId);
            }
            if (sellerInsuranceProductId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerInsuranceProductID == sellerInsuranceProductId);
            }
            if ((byte)status > 0)
            {
                expressionWhere = expressionWhere.And(o => o.Status == (byte)status);
            }
            var list = LoadEntities(expressionWhere);
            return list.Any() ? list.Sum(o => o.BuyCount) : 0;
        }

        /// <summary>
        /// 获取同一身份证已购买产品的数量（不能超过限制的量）
        /// </summary>
        /// <param name="sellerInsuranceProductID"></param>
        /// <param name="buyUserIDNo"></param>
        /// <returns></returns>
        public int GetIdentityCardHasBuyQty(long sellerInsuranceProductID, string buyUserIDNo)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrder>();
            expressionWhere = expressionWhere.And(o => o.SellerInsuranceProductID == sellerInsuranceProductID && o.BuyUserIDNo.Equals(buyUserIDNo) && o.Status == (byte)InsuranceProductOrderStatus.Paid);
            var list = LoadEntities(expressionWhere);
            return list.Any() ? list.Count() : 0;
        }
    }
}
